package com.pizidea.imagepicker.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.core.VoicePlayer;
import com.efounder.mobilecomps.R;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pizidea.imagepicker.Mp3DownloadUtils;
import com.pizidea.imagepicker.ui.LoadingDataUtilBlack;
import com.zhuiji7.filedownloader.download.DownLoadManager;

import org.angmarch.views.WaveView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * create by meijun
 */
public class ShowProofActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView mListView;
    private MyBaseAdapter myBaseAdapter;
    String url = "http://mobile.osp.cloud/OSPMobile/CtrlService?action=loadFile&fwk=FormAffixService&iom=loadAffixData&PO=DataBaseName=ZYYT_DB01;DBNO=ZYHYGL01&FileName=F_NAME&GUID=F_GUID&ORDE=F_ORDE&MDLID=GDPGModel&affixTable=SYS_MDL_AFFIX_GDPGModel&affixTableB=SYS_MDL_AFFIXB_GDPGModel&CCLX=FILE&PATH=F_PATH&SWF_FILE=0&PDF_FILE=0&WJLX=2&AFFIX_WHERE=&F_FLFCT=&F_FLBH=";
    private List<Holder> list_data = new ArrayList<Holder>();

    //音频文件下载;
    private DownLoadManager downLoadManager;

    //播放视频组件
    VoicePlayer  voicePlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_proof);

        mListView = (ListView) findViewById(R.id.listview);
        final TextView finish_button = (TextView) findViewById(R.id.finish_button);

            finish_button.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int intrinsicWidth = finish_button.getCompoundDrawables()[0].getIntrinsicWidth();
                    int intrinsicHeight = finish_button.getCompoundDrawables()[0].getIntrinsicHeight();
                    if(event.getX()< intrinsicWidth && event.getY() < intrinsicHeight){
                        finish();
                    }

                    return true;
                }
            });
        myBaseAdapter = new MyBaseAdapter(getLayoutInflater(), list_data);
        mListView.setAdapter(myBaseAdapter);
        mListView.setOnItemClickListener(this);
        voicePlayer = new VoicePlayer(this.getApplicationContext(), new Handler());

        ArrayList<String> value = getIntent().getStringArrayListExtra("value");
        if (value != null) {

            for (String valu : value) {
                String[] split = valu.split("&&");
                String uri = url.replace("F_NAME", split[0]).replace("F_GUID", split[1]).replace("F_PATH", split[2]).replace("F_ORDE", split[3]);
                list_data.add(new Holder(split[0], uri, split[1]));
            }
        }
        myBaseAdapter.notifyDataSetChanged();
        downLoadManager = new DownLoadManager(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, final View view, int position, long l) {
        int itemViewType = myBaseAdapter.getItemViewType(position);
        final Holder holder = list_data.get(position);
        if (holder.isImage()) {
            //是图片
            Intent intent = new Intent(this, ShowImageActivity.class);
            intent.putExtra("uri", holder.getUri());
            startActivity(intent);
        } else {
            //是录音;
            final File file = new File(holder.getPath(), holder.name);
            if (file.exists()) {
                playmusic(file, view);
                //直接播放音乐
            } else {
                //下载文件;
                LoadingDataUtilBlack.show(ShowProofActivity.this);
                Mp3DownloadUtils.downLoadFiles(this, holder.getUri(), file.getAbsolutePath(), new Mp3DownloadUtils.DownloadListener() {
                    @Override
                    public void onSuccess(String path) {
                        LoadingDataUtilBlack.dismiss();
                        Log.e(TAG, "onSuccess: "+path );
                        Log.e(TAG, "onSuccess: fiel "+file.getAbsolutePath() );
                        ShowProofActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                            playmusic(file, view);
                            }
                        });
                    }

                    @Override
                    public void onFailure() {
                        LoadingDataUtilBlack.dismiss();
                        ToastUtil.showToast(ShowProofActivity.this, ResStringUtil.getString(R.string.common_text_network_error));
                    }
                });

            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        //当界面不显示时,语音播放组件要重置;
        if(voicePlayer!=null){

        voicePlayer.resetPlayer();
        }


    }

    private static final String TAG = "ShowProofActivity";
    /**
     * 播放音乐;
     * 更改UI界面
     *
     * @param
     * @param view
     */
    private void playmusic(File file, View view) {

        Log.e(TAG, "playmusic: "+ file.getAbsolutePath());
        if(!file.exists()){
            return ;
        }
        final WaveView waveview = (WaveView) view.findViewById(R.id.waveView);

        final View imageview = view.findViewById(R.id.imageview);
        imageview.setVisibility(View.INVISIBLE);
        waveview.setWaveHeight(0.2f);
        waveview.setVisibility(View.VISIBLE);


        voicePlayer.playVoice(file.getAbsolutePath());
        voicePlayer.setonStateChangeListener(new VoicePlayer.OnstateChangeListener() {
            @Override
            public void playComplete() {
                imageview.setVisibility(View.VISIBLE);
                waveview.setVisibility(View.INVISIBLE);

            }
        });
    }

    public static class MyBaseAdapter extends BaseAdapter {

        private List<Holder> list_data;
        LayoutInflater mInflater;

        public MyBaseAdapter(LayoutInflater inflater, List<Holder> list_data) {
            this.mInflater = inflater;
            this.list_data = list_data;
        }

        @Override
        public int getCount() {
            return list_data == null ? 0 : list_data.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }


        @Override
        public long getItemId(int i) {
            return 0;
        }


        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View list_item_view = mInflater.inflate(R.layout.activity_proof_listview_item, null);
            TextView name = (TextView) list_item_view.findViewById(R.id.name);
            ImageView imageview = (ImageView) list_item_view.findViewById(R.id.imageview);


            Holder holder = list_data.get(i);
            if (holder.isImage()) {

                Glide.with(imageview.getContext())
                        .load(holder.uri)
                        .apply(new RequestOptions().centerCrop()
                                .dontAnimate()
                                .placeholder(R.drawable.default_img)
                                .error(R.drawable.default_img))
                        .thumbnail(0.5f)

                        .into(imageview);

            } else {
                imageview.setImageResource(R.drawable.music);
            }

            name.setText(holder.getName());

            return list_item_view;
        }
    }

    class Holder {
        private String guid;
        private String name;
        private String path;
        private String uri;
        private boolean isImage = false;

        public boolean isImage() {

            return isImage;

        }


        public String getPath() {

            return path;
        }

        public String getName() {
            return name;
        }

        public String getUri() {
            return uri;
        }

        public Holder(String name, String uri, String guid) {
            this.name = name;
            this.uri = uri;
            this.guid = guid;

            isImage = name.contains("png") || name.contains("jpg") || name.contains("jpeg");

            //如果事音频文件,为每个文件分配存储位置;

            if (!isImage()) {

                File downloadCacheDirectory = Environment.getExternalStorageDirectory();
                if (downloadCacheDirectory == null) {
                    return;
                }
                File file = new File(downloadCacheDirectory, "OSPMoblie" + File.separator + guid);
                if (!file.exists()) {
                    file.mkdirs();
                }

                path = file.getAbsolutePath();


            }

        }


    }


}


